﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using AutoTestEntry.Data;
using AutoTestEntry.Utility;

namespace AutoTestEntry.SpecificUtility
{
    class EnvDepoly
    {
        private String SVN_DOWNLOAD_TYPE = "SvnDownload";
        private String NET_DOWNLOAD_TYPE = "NetDownload";
        private String NUNIT_DOWNLOAD_TYPE = "NUnitDownload";
        
        private FtpDownloader ftpDownloader;
        private Installer installer;

        #region Init 
        public EnvDepoly()
        {
             ftpDownloader = new FtpDownloader();
             ftpDownloader.DownloadEvent += DownloadEventHandler;

             installer = new Installer();
             installer.InstallFinishedEvent += InstallFinishedHandler;
        }
        #endregion

        #region Self Defined Events
        public class NewInfoEventArgs : EventArgs
        {
            public readonly String Info;
            public NewInfoEventArgs(String info)
            {
                Info = info;
            }
        }

		public class LastLineChangedEventArgs : EventArgs
		{
			public readonly String Info;
			public LastLineChangedEventArgs(String info)
			{
				Info = info;
			}
		}

        public delegate void NewInfoEventHandler(Object sender, NewInfoEventArgs e);
        public event NewInfoEventHandler NewInfoEvent;

		public delegate void LastLineChangedEventHandler(Object sender, LastLineChangedEventArgs e);
		public event LastLineChangedEventHandler LastLineChangedEvent;

		public delegate void AutoDeployFinishedEventHandler(Object sender, EventArgs e);
		public event AutoDeployFinishedEventHandler AutoDeployFinishedEvent;
        #endregion

        #region Check if the environment is ready
        public bool CheckEnvironment()
        {
            if (IsNet3_5Exists() && IsSVNExist() && 
				IsNUnitExists() && IsDestSetted())
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        private bool IsNet3_5Exists()
        {
			return File.Exists(GlobalInfo.LocalNetPath);
        }

        private bool IsSVNExist()
        {
            return File.Exists(GlobalInfo.LocalSvnPath);
        }

        private bool IsNUnitExists()
        {
            return File.Exists(GlobalInfo.LocalNUnitPath);
        }

        private bool IsDestSetted()
        {
            return Directory.Exists(GlobalInfo.LocalDestPath);
        }
		#endregion

		#region public info about the envrionment
        public String[] GetEnvrinment()
        {
            String[] result = new String[4]{"","","",""};
            if (IsNet3_5Exists())
            {
                result[0] = GlobalInfo.LocalNetPath;
            }
            if (IsSVNExist())
            {
                result[1] = GlobalInfo.LocalSvnPath;
            }
            if (IsNUnitExists())
            {
                result[2] = GlobalInfo.LocalNUnitPath;
            }
            if (IsDestSetted())
            {
                result[3] = GlobalInfo.LocalDestPath;
            }
            return result;
        }

		public void SetSvnUserNameAndPasswd(String userName, String passwd)
		{
			GlobalInfo.SvnUserName = userName;
			GlobalInfo.SvnPassword = passwd;
			GlobalInfo.SaveLocalInfo();
		}

		public void SetFtpAdress(String ftp)
		{
			GlobalInfo.FtpAddress = ftp;
			GlobalInfo.SaveLocalInfo();
		}

		public void SetEnvironment(String netPath, String svnPath, String nunitPath, String destPath)
		{
			GlobalInfo.LocalNetPath = netPath;
			GlobalInfo.LocalSvnPath = svnPath;
			GlobalInfo.LocalNUnitPath = nunitPath;
			GlobalInfo.LocalDestPath = destPath;

			GlobalInfo.SaveLocalInfo();

		}

		public String GetVersion()
		{
			return GlobalInfo.Version;
		}

		public String GetLocalUpdateExePath()
		{
			return GlobalInfo.UpdateExePath;
		}

		public String GetFtpNewVersionPath()
		{
			return GlobalInfo.FtpAddress + "/" + GlobalInfo.FtpNewVersionSoftPath;
		}

		public String GetFtpAddress()
		{
			String[] parts = GlobalInfo.FtpAddress.Split(new Char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);

			if (parts.Length == 2)
			{
                parts = parts[1].Split(new char[]{'@'}, StringSplitOptions.RemoveEmptyEntries);
                if (parts.Length == 2)
                {
                    return parts[1];
                }
                else if (parts.Length == 1)
                {
                    return parts[0];
                }
                else
                {
                    return "";
                }
			}
			else
			{
				return "";
			}
		}

        public String GetFtpUserName()
        {
            String[] parts = GlobalInfo.FtpAddress.Split(new Char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);

            if (parts.Length == 2)
            {
                parts = parts[1].Split(new char[] { ':', '@' });
                if (parts.Length == 3)
                {
                    return parts[0];
                }
                else
                {
                    return "";
                }
            }
            else
            {
                return "";
            }
        }

        public String GetFtpPasswd()
        {
            String[] parts = GlobalInfo.FtpAddress.Split(new Char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);

            if (parts.Length == 2)
            {
                parts = parts[1].Split(new char[] { ':', '@' });
                if (parts.Length == 3)
                {
                    return parts[1];
                }
                else
                {
                    return "";
                }
            }
            else
            {
                return "";
            }
        }
        #endregion

        #region AutoDeploy  Download fils from ftp and auto install
        public void AutoDeploy()
        {
			if (!IsNet3_5Exists())
			{
				NewInfoEvent(this, new NewInfoEventArgs("开始下载 .Net 3.5..." + Environment.NewLine + "已下载 0%" + Environment.NewLine));
				ftpDownloader.Download(GlobalInfo.FtpAddress + "/" + GlobalInfo.FtpNetPath, GlobalInfo.SaveNetDir, true, NET_DOWNLOAD_TYPE);
			}
			if (!IsSVNExist())
            {
				NewInfoEvent(this, new NewInfoEventArgs("开始下载 SVN..." + Environment.NewLine + "已下载 0%" + Environment.NewLine));
                ftpDownloader.Download(GlobalInfo.FtpAddress + "/" + GlobalInfo.FtpSvnPath, GlobalInfo.SaveSvnDir, false, SVN_DOWNLOAD_TYPE);
            }
			if (!IsNUnitExists())
            {
				NewInfoEvent(this, new NewInfoEventArgs("开始下载 NUnit..." + Environment.NewLine + "已下载 0%" + Environment.NewLine));
                ftpDownloader.Download(GlobalInfo.FtpAddress + "/" + GlobalInfo.FtpNUnitPath, GlobalInfo.SaveNunitDir, false, NUNIT_DOWNLOAD_TYPE);
            }
            if (!IsDestSetted())
            {
                Directory.CreateDirectory(GlobalInfo.LocalDestPath);
            }

			AutoDeployFinishedEvent(this, new EventArgs());
        }

        private void DownloadEventHandler(Object sender, FtpDownloader.DownloadEventArgs e)
        {
			LastLineChangedEvent(this, new LastLineChangedEventArgs("已下载 " + e.FinishedPercent + "%"));
            if (e.FinishedPercent == 100)
            {
                if (e.Type.Equals(NET_DOWNLOAD_TYPE))
                {
					NewInfoEvent(this, new NewInfoEventArgs("!!!.Net 下载完成，请自行安装，保存在 " + GlobalInfo.SaveNetDir + Environment.NewLine));
                }
                else if (e.Type.Equals(SVN_DOWNLOAD_TYPE))
                {
                    NewInfoEvent(this, new NewInfoEventArgs("SVN部署完成" + Environment.NewLine));
                }
                else if (e.Type.Equals(NUNIT_DOWNLOAD_TYPE))
                {
					NewInfoEvent(this, new NewInfoEventArgs("NUnit部署完成" + Environment.NewLine));
                }
            }
        }

        private void InstallFinishedHandler(Object sender, Installer.InstallFinishedEventArgs e)
        {
            
        }
        #endregion  

        #region Import from .bat file
		public bool ImportSettings(String[] envs)
		{
			for (int i = 0; i < envs.Length; ++i)
			{
				if (envs[i] == "")
				{
					return false;
				}
			}

			GlobalInfo.LocalNetPath = envs[0];
			GlobalInfo.LocalSvnPath = envs[1];
			GlobalInfo.LocalNUnitPath = envs[2];
			GlobalInfo.LocalDestPath = envs[3];

			GlobalInfo.SaveLocalInfo();
			return true;
		}

        public String[] GetEnvrinmentFromBat(String path)
        {
            if (!File.Exists(path))
            {
                return null;
            }

            String[] result = new String[4] {"", "", "", ""};
			
			// 设置语言
            StreamReader sr = new StreamReader(path, System.Text.Encoding.Default);
            while (!sr.EndOfStream)
            {
                String line = sr.ReadLine().Trim();
                if (line.Length > 3)
                {
					String[] temps = line.Split(new char[] { ' ', '	' }, StringSplitOptions.RemoveEmptyEntries);
                    if (temps[0].ToLower().Equals("set"))
                    {
                        //TODO 解析set
                        line = line.Substring(4).Trim();
                        String[] settings = line.Split(new char[]{'=', '\"'}, StringSplitOptions.RemoveEmptyEntries);
						if (settings.Length < 2)
						{
							continue;
						}

						if (settings[0].ToUpper().Equals("NET_PATH"))
						{
							result[0] = settings[1] + "\\MSbuild.exe";
							if (!File.Exists(result[0]))
							{
								result[0] = "";
							}
						}
						else if (settings[0].ToUpper().Equals("SVN_PATH"))
						{
							result[1] = settings[1] + "\\svn.exe";
							if (!File.Exists(result[1]))
							{
								result[1] = "";
							}
						}
						else if (settings[0].ToUpper().Equals("NUNIT_PATH"))
						{
							result[2] = settings[1] + "\\nunit.exe";
							if (!File.Exists(result[2]))
							{
								result[2] = "";
							}
						}
						else if (settings[0].ToUpper().Equals("DEST_PATH"))
						{
							result[3] = settings[1];
							if (!Directory.Exists(result[3]))
							{
								result[3] = "";
							}
						}
                    }
                }
            }
            return result;
        }
        #endregion
    }
}